<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>验证码</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.js"></script>
</head>
<style>
    body {
        text-align: center;
    }
</style>
<body>
<div id="notification" origin-msg="验证结果：">验证结果：</div>
<label for="captchaResultInput">输入验证码的计算结果：</label>
<input id="captchaResultInput" type="text" placeholder="计算结果"/>
<button id="verifyCaptcha" type="button">验证</button>
<p><img src="" id="captchaImg" alt=""/></p>
</body>
<script>
    let captchaKey;

    // 定义调用获取验证码的函数
    let generateCodeFun = function () {
        // 获取验证码
        $.get("/test/hutoolCaptcha/mathCode", function (res) {
            captchaKey = res.captchaKey;
            $("#captchaImg").attr("src", res.image);
        }, "json");
    }

    // 初始先生成一个验证码
    generateCodeFun();

    //每次点击图片就生成新的验证码
    $("#captchaImg").click(
        generateCodeFun
    )

    // 点击验证按钮就执行验证
    $("#verifyCaptcha").click(function () {
        // 执行验证
        $.get("/test/hutoolCaptcha/verifyCode", {
            captchaKey: captchaKey,
            captchaResult: $("#captchaResultInput").val()
        }, function (res) {
            // 设置验证结果
            let $notification = $("#notification");
            let originText = $notification.attr("origin-msg");
            if (res.code === "200") {
                $notification.text(originText + "正确");
            } else {
                $notification.text(originText + "错误");
            }
        }, "json");
        // 无论结果如何，都去刷新验证码
        generateCodeFun();
    })
</script>
</html>